        //
//  AudioPlayer.m
//  LO_MUSIC
//
//  Created by lanou3g on 16/2/26.
//  Copyright © 2016年 徐强. All rights reserved.
//

#import "AudioPlayer.h"
#import <AVFoundation/AVFoundation.h>

static AudioPlayer *audioPlayer = nil;
@interface AudioPlayer()
//播放器
@property (nonatomic, strong)AVPlayer *localPlayer;

@property (nonatomic,assign,getter=isCurrentPlaying) BOOL currentPlaying;
//控制进度条的计时器
@property (nonatomic,strong ) NSTimer *timer;

@end


@implementation AudioPlayer
//是否正在播放（isPlaying只读，通过currentPlaying来改变isPlaying的值）
- (BOOL)isPlaying{
    return self.isCurrentPlaying;
}
//1. 文件是单例
+ (instancetype)shareAudioPlayer
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        audioPlayer = [[AudioPlayer alloc]init];
    });
    return audioPlayer;
}

- (instancetype )init{
    self = [super init];
    if (self) {
        //接收AVPlayer播放完成的通知
        //系统发出的通知
        [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    }
    return self;
}
//接收播放结束的通知后调用的方法
- (void)playEnd{
    //播放结束
    if (self.delegate && [self.delegate respondsToSelector:@selector(playFinish)]) {
        [self.delegate playFinish];
    }
}

//2. 播放
- (void)playWithUrl:(NSString *)url
{
    //移除监听状态
    [self.localPlayer.currentItem removeObserver:self forKeyPath:@"status" context:nil];
    
    //创建一个播放对象
    AVPlayerItem *item = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    
    //1.监听者 2.监听的属性 3.新值，旧值 4.附加信息
    [item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld) context:nil];
    
    //播放
     [self.localPlayer replaceCurrentItemWithPlayerItem:item];
//    //纪录此时的播放状态
//    self.currentPlaying = YES;
}
//监听者自带的触发方法
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context{
    //如果监听的属性不是status，直接返回
    if (![keyPath isEqualToString:@"status"]) {
        return;
    }
    //取出变化的值
    AVPlayerItemStatus value = [change[@"new"] integerValue];;
    if (value == AVPlayerItemStatusReadyToPlay) {
        //准备好了播放音乐
        [self play];
    }else{
        //准备失败／准备情况不知道
    }
}
//3. 暂停/恢复
- (void)playOrPause
{
    //直接调用系统提供的API
    if (self.isPlaying) {
        //暂停
        [self pause];
    }else{
        //播放
        [self play];
    }
}
//播放
- (void)play{
#pragma mark - 播放前清空timer，防止计时器
    [self.timer invalidate];
    self.timer = nil;
    //播放
    [self.localPlayer play];
    self.currentPlaying = YES;
    //进度条
    self.timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
}
//暂停
- (void)pause{
    //暂停
    [self.localPlayer pause];
    //纪录状态
    self.currentPlaying = NO;
    //清空time
    [self.timer invalidate];
    self.timer = nil;
}
//timerAction
- (void)timerAction{
    if (self.delegate && [self.delegate respondsToSelector:@selector(playWithTime:)]) {
        CGFloat time = self.localPlayer.currentTime.value * 1.0 / self.localPlayer.currentTime.timescale;
        [self.delegate playWithTime:time];
    }
}

//4. 停止
- (void)stop
{
    //把时间设置为0
    [self.localPlayer seekToTime:CMTimeMake(0, self.localPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {//设置完毕
            [self pause];
        }
    }];
}
//5. 从什么时候开始播放
- (void)seekToTime:(CGFloat)time
{
    //先暂停
    [self pause];
    //设置从什么位置开始播放
   // self.localPlayer seekToTime:CMTimeMakeWithSeconds(<#Float64 seconds#>, <#int32_t preferredTimeScale#>)
    [self.localPlayer seekToTime:CMTimeMakeWithSeconds(time, self.localPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
        if (finished) {
            //播放
            [self play];
        }
    }];
//    [self.localPlayer seekToTime:CMTimeMake(time, self.localPlayer.currentTime.timescale) completionHandler:^(BOOL finished) {
//        if (finished) {
//            //播放
//            [self play];
//        }
//    }];
    
}
//获取音量
- (CGFloat)volume{
    return self.localPlayer.volume;
}
//设置音量
- (void)setVolume:(CGFloat)volume{
    self.localPlayer.volume = volume;
}
//懒加载
- (AVPlayer *)localPlayer{
    if (!_localPlayer) {
        _localPlayer = [[AVPlayer alloc]init];
        _localPlayer.volume = 0.5;//初始化音量
    }
    return _localPlayer;
}

@end
